#include <iostream>
#include <sys/types.h>
#include <cerrno>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>

using namespace std;

class Socket
{
public:
    // 1.创建套接字
    static int Sock()
    {
        int fd = socket(AF_INET, SOCK_STREAM, 0);
        if (fd < 0)
        {
            cout << "socket create error" << errno << endl;
            exit(1);
        }
        return fd;
    }

    // 2.绑定IP和端口号
    static void Bind(int sock, uint16_t port)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            cout << "bind error" << errno << endl;
            exit(2);
        }
    }

    // 3.监听连接
    static void Listen(int sock)
    {
        if (listen(sock, 5) < 0)
        {
            cout << "listen error" << errno << endl;
            exit(3);
        }
    }

    // 4.获取连接
    static int Accept(int sock)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(sock, (struct sockaddr *)&peer, &len);
        if (newfd < 0)
        {
            cout << "accept error" << errno << endl;
            exit(4);
        }
        return newfd;
    }

    // 5.发送链接
    static void Connect(int fd, string ip, uint16_t port)
    {
        struct sockaddr_in sever;
        sever.sin_family = AF_INET;
        sever.sin_addr.s_addr = inet_addr(ip.c_str());
        sever.sin_port = htons(port);
        if (connect(fd, (struct sockaddr *)&sever, sizeof(sever)) == 0)
        {
            cout << "connect success!" << endl;
        }
        else
        {
            cout << "connect error" << endl;
            exit(5);
        }
    }
};
